/*********************************************************************************
 *      Copyright:  (C) 2024 LiYi<1751425323@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  ifconfig.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(25/04/24)
 *         Author:  LiYi <1751425323@qq.com>
 *      ChangeLog:  1, Release initial version on "25/04/24 11:16:43"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

#include "ifconfig.h"


int get_ipaddr(char *interface,char *ipaddr,int ipaddr_size)
{
	char            buf[1024];
	char            *ptr;
	char            *ip_start;
	char            *ip_end;
	FILE            *fp;
	int             len;
	int             rv;

	if(!interface || !ipaddr || ipaddr_size <16)
	{
		printf("Invalid input argument\n");
		return -2;
	}

	memset(buf, 0 , sizeof(buf));
	snprintf(buf,sizeof(buf),"ifconfig %s",interface);
	fp = popen(buf,"r");
	if(NULL==fp)
	{
		printf("popen() to extern command\"%s\"failure:%s\n",buf,strerror(errno));
		return -2;
	}
	rv = -3;
	while(fgets(buf,sizeof(buf),fp))
	{
		if(strstr(buf,"netmask"))
		{
			ptr = strstr(buf,"inet");
			if(!ptr)
			{
				break;
			}
			ptr +=strlen("inet");

			while(isblank(*ptr))
				ptr++;
			ip_start = ptr;
			while(!isblank(*ptr))
				ptr++;
			ip_end = ptr;
			memset(ipaddr,0,sizeof(ipaddr));

			len = ip_end-ip_start;
			len = len>ipaddr_size ? ipaddr_size:len;

			memcpy(ipaddr,ip_start,len);
			rv = 0;

			break;
		}
	}
	pclose(fp);
	return rv;
}

